console.log('tax injected');

import { transformDataByOpenWeb } from './../../lib/openWebTransform.js';


let baseInfoCache;
let info = {};


// 监听url hash 和 history 改变
window.addEventListener('hashchange', hashChangeFire);

window.addEventListener('popstate', function(event) {
  hashChangeFire();
});

let _wr = function(type) {
  var orig = window.history[type];
  return function() {
    var rv = orig.apply(this, arguments);
    var e = new Event(type);
    e.arguments = arguments;
    window.dispatchEvent(e);
    return rv;
  };
};
window.history.pushState = _wr('pushState');
window.history.replaceState = _wr('replaceState');

window.addEventListener('replaceState', function(e) {
  hashChangeFire();
});
window.addEventListener('pushState', function(e) {
  hashChangeFire();
});

function hashChangeFire () {
  window.location.reload();
}

function getNewInfo () {
  // 更新填报信息
  if (/rm-neimenggu.taxplusplus.com/g.test(window.location.href)) {
    window.postMessage(
      {
        event: 'getBaseInfo'
      },
      '*'
    );
    let TaxTable = document.querySelector('#menu');
    const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
    let options = {
      childList: true
    };
    let tableList = new MutationObserver((records) => {
      records.map(item => {
        if (item.addedNodes.length) {
          sendInfo({
            type: item.addedNodes[0].querySelector('tr > td').textContent
          });
        }
        return item;
      });
    });
    let mo = new MutationObserver((records) => {
      records.map(item => {
        if (item.previousSibling && item.previousSibling.className === 'ant-col-19') {
          let table = item.previousSibling;
          let taxTime = table.childNodes[0].textContent.match(/\d{1,4}/g);
          taxTime = taxTime.map(it => {
            return parseInt(it) > 9 ? it : '0' + it;
          });
          let startTime = `${taxTime[0]}-${taxTime[1]}`;
          let endTime = `${taxTime[3]}-${taxTime[4]}`;
          sendInfo({
            startTime, endTime
          });
          tableList.observe(table.children[0], options);
        }
        return false;
      });
    });
    mo.observe(TaxTable, options);
  }
}

window.onload = function() {
  // 登录界面填写账号密码
  if (/login-web\/index.html/g.test(window.location.pathname)) {
    window.postMessage(
      {
        event: 'getBaseInfo'
      },
      '*'
    );
  }
  getNewInfo();
};

function sendInfo({ startTime = '', endTime = '', type = '' }) {
  if (startTime) info.startTime = startTime;
  if (endTime) info.endTime = endTime;
  if (type) info.type = type;
  if (info.startTime && info.endTime && info.type) {
    if (info.type.search('利润表') > -1) {
      type = 'profit';
    } else if (info.type.search('现金流量表') > -1) {
      type = 'cash';
    } else {
      type = 'balance';
    }
    window.postMessage(
      {
        event: 'setPeriodAndType',
        data: {
          ...info,
          type
        }
      },
      '*'
    );
  }
}

window.addEventListener(
  'message',
  async function({ data }) {
    // 只监听来自于content script的信息
    if (data.sender !== 'content-script') {
      return false;
    }
    if (data.event === 'getNationData') {
      getNationData(data.data.taxType);
    }
    if (data.event === 'getBaseInfo') {
      baseInfoCache = data.data;
      if (/login-web\/index.html/g.test(window.location.pathname)) {
        autoInputAccount(baseInfoCache);
      }
    }
    if (data.event === 'setSaasData') {
      let dataInfo = data.data;
      let sheet = dataInfo.saasData.sheet;
      fillInput(await transformDataByOpenWeb(dataInfo), sheet);
    }
  },
  false
);

function fillInput({ saasData, baseInfo }) {
  let message = '';
  if (saasData.data.type === 'file') {
    message = downloadFile(saasData.data.data, baseInfo);
  } else {
    message = '不支持json方式，下载文件失败！';
  }

  window.postMessage({
    event: 'fillInputDone',
    data: {
      message: message || '下载文件成功'
    }
  }, '*');
}

/**
 * 下载文件
 * @param blob
 */
function downloadFile(blob, { taxInfo, popupParams }) {
  blob = new Blob([blob], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  let a = document.createElement('a');
  // 指定生成的文件名
  // let name = `${taxInfo.nsrsbh}_${taxInfo.institution === '2013' ? 'ZL019' : 'ZL001'}`;
  let { nsrmc = '' } = taxInfo;

  const start = taxInfo.skssqq.replace(/-/g, '');
  const end = taxInfo.skssqz.replace(/-/g, '');
  a.download = `${nsrmc}_${start}_${end}.xlsx`;
  a.href = URL.createObjectURL(blob);
  document.body.appendChild(a);
  a.click();
}

function autoInputAccount({ companyInfo }) {
  companyInfo = companyInfo || {};
  document.getElementById('userName1').value = companyInfo.nationalTaxAccount || companyInfo.nationalTaxId;
  document.getElementById('passWord1').value = companyInfo.nationalTaxPass;
}

/**
 * 调用接口获取公司信息
 */
function getNationData(taxType) {
  // if (!(/rm-neimenggu.taxplusplus.com\/risk\/tax-data-details/g.test(window.location.href))) {
  //   alert('请前往报税页面导出报税');
  //   return false;
  // }
  if (!baseInfoCache || !baseInfoCache.companyInfo.nationalTaxId) {
    alert('纳税人识别号不能为空，请前往crm设置');
    return false;
  }
  let taxInfo = {
    institution: baseInfoCache.companyInfo.institutionCode === '2' ? '2013' : '2007', // 国税对应制度 2007 | 2013
    nsrsbh: baseInfoCache.companyInfo.nationalTaxId, // 纳税人申报号
    nsrmc: baseInfoCache.companyInfo.companyName, // 纳税人名称（纳税公司）
    skssqq: '', // 税款所属期起
    skssqz: '', // 税款所属期止
    isZip: true,
    isHsqjSmall: false, // 是否为小微企业汇算清缴
    outPutType: 'excel' // 填报方式
  };
  window.postMessage(
    {
      event: 'backNationData',
      data: {
        taxInfo: taxInfo
      }
    },
    '*'
  );
}
